import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-03-31
 * Time: 9:26
 */
public class TestJDBCSelect {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2.建立连接
        Connection connection = dataSource.getConnection();

        //3.拼装 SQL
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4.执行 ,对于查询操作,需要使用executeQuery
        //查询操作返回值不是int ,而是一个临时表
        //使用ResultSet 表示这个表
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集合(返回的临时表),获取到每一行,再获取到这一行的若干列
        // next()方法会自动跳转到下一行
        while (resultSet.next()) {//拿到某一行
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id=" + id + ",name="+name);
        }

        //6.释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
